var baseUrl = _ctx + '/cfgmgr/card/';
var CFG_CARD = _ctx + '/cfg/card/';
//和后台字典配置一致
var TYPE_WITH_UNIT = '3';
var TYPE_DICT = '7';
var TYPE_DICT_TRANS = '11';

var paramList = '';

$(document).ready(function() {
		paramList = getParamList();
		initUI();
		loadDBData();
		updateRemoteData(_cid, paramList, true);
});

/**
 * 界面初始化
 */
function initUI(){
	$('#tab_nav').tabs();		
	$('.btn-reset').click(function(){
		var fieldCtrl = $(this).parent().find("[uname='update']");
		var paramName = fieldCtrl.attr('id');
		var value = parent.commonAPI.INITIAL_MAP[paramName];
		fieldCtrl.val(value);		
		//清除标记
		hideErrIcon(fieldCtrl);
	});
	//同步操作
	$('.btn-sync').click(function(){
		var paramName = $(this).parent().find("[uname='update']").attr('id');
		//更新提交对象中
		updateRemoteData(_cid, paramName, false);
	});
	
	//提交保存操作
	$('.btn-confirm').click(function(){
		var paramStr = '';		
		//修改更新后的
		$('.changedValueList').each(function(index,data){
			if($(data).val()!=""){
					var list = JSON.parse($(data).val());
					for(key in list){
						//var value = list[key];				
						var field = $("[name='" + key +  "']");				
						if ( field.attr('utype')==TYPE_WITH_UNIT ) {
							var rate = (field.attr('uunit') == "") ? 1 : field.attr('uunit');
							list[key] = (list[key]/rate).toFixed(0) ;
						} else {
							list[key] = list[key];
						}
					};
					//paramStr += $(data).val() ;
					paramStr += JSON.stringify(list);
			}
		});
		
		//paramStr = getAllValue();
		
		if(paramStr != '') {
			var afterFunc = parent.commonAPI.info;
			var paramList = ['通知', '板卡参数保存成功。'];
			parent.commonAPI.progress(0,'板卡所有参数已下发，等待设备响应....', afterFunc, paramList);
			
			var url = CFG_CARD + 'saveData/' + _cid;
			var ajaxSetting = 
				{
					url:url, 
					type:'post',
					data:'jsonData=' + paramStr,
					success:function(result){
						$(paramList).each(function(index, key){					
							$('#' + key).val(result[key]);
							parent.commonAPI.INITIAL_MAP[key] = result[key];
						});
			}};
			parent.commonAPI.ajaxProgress('读取网元板卡信息，等待设备响应....', ajaxSetting);
		} else {
			parent.commonAPI.warn('错误','不能提交空白参数。');
		}
		
	});
	
	$('.nav-tabs a:first').tab('show');
}

function onQuery(){
	
}

/**
 * 从数据库读取板卡参数
 */
function loadDBData(){
	//CardType
	//var paramStr = 'CardType|HardwareRev|FirmwareRev|SerialNum|MfgDate|CalDate';
	var url = CFG_CARD + 'updateData/' + _cid;
	var ajaxSetting = {url:url, type:'get',
			success:function(result){
				$(paramList).each(function(index, key){					
					$('#' + key).val(result[key]);
					parent.commonAPI.INITIAL_MAP[key] = result[key];
				});
	}};
	parent.commonAPI.ajaxProgress('读取网元板卡信息，等待设备响应....', ajaxSetting);
}

/**
 * 读取板卡实时数据  
 */
function updateRemoteData(cid, params, isInit) {
	var url = CFG_CARD + 'remote/' + cid;
	$.ajax({
		url : url,
		type : 'post',
		data : 'jsonData=' + params,
		success : function(resultData) {
			var paramList = getParamList();
			$(paramList).each(
					function(index, fieldName) {
						var field = $("[name='" + fieldName +  "']");
						var fieldValue = field.val();
						var respValue = resultData[fieldName];
						if ((respValue != undefined || respValue != null)) {
							//换算值
							if(!isInit) {
								if ( field.attr('utype')==TYPE_WITH_UNIT ) {
									var rate = (field.attr('uunit') == "") ? 1 : field.attr('uunit');
									respValue = (respValue*rate).toFixed(1);
								}
							} 
							// 检查值是否相同
							if (fieldValue != respValue && field.attr('readOnly') != 'readonly') {								
								addErrIcon(field);								
							} else {
								// 删掉
								hideErrIcon(field);
							}
							if(isInit) {
								if ( field.attr('utype')==TYPE_WITH_UNIT ) {
									var rate = (field.attr('uunit') == "") ? 1 : field.attr('uunit');
									respValue = (respValue*rate).toFixed(1);
								}
							} 
							field.val(respValue);
							
							//如果带单位，换算单位								
//							if ( field.attr('utype')==TYPE_WITH_UNIT ) {
//								var rate = (field.attr('uunit') == "") ? 1 : field.attr('uunit');
//								field.val(respValue*rate);
//							} else 
							if(field.attr('utype')==TYPE_DICT) {
								//设置select控件状态
								$(field).find('option').each(function(index, data){
									if($(data).val() == respValue){
										$(data).attr('selected','selected');
										$(field).trigger('liszt:updated');
									}
								});
							} else if(field.attr('utype') == TYPE_DICT_TRANS) {	
								var v = getDictLabel(respValue, _dictTable);
								$(field).val(v);
							}
						}
					});
		}
	});
}

/**
 * 查询字典标签 
 * @param value
 * @param list
 * @returns
 */
function getDictLabel(value, list){
	var result = '';
	$(list).each(function(index,data){
		if(data.value == value){
			result = data.label;
		}
	});
	return result;
}

/**
 * 增加错误提示框
 * @param field
 */
function addErrIcon(field){
	var options = {
			animation : true,
			trigger : 'hover' // 触发tooltip的事件
	};
	var errIcon = field.parent().find('.icon-remove-sign');
	var isHidden = errIcon.css('visibility');
	if(isHidden == undefined) {
		field.parent().append($("<i class='icon-remove-sign'></i>"));
	} else if(isHidden == 'hidden') {
		errIcon.css('visibility', '');
	}
	field.parent().parent().addClass('has-error');
	field.popover(options);
	//修改同步的值
	//setChangeValue(field);
}

/**
 * 隐藏错误提示框
 * @param field
 */
function hideErrIcon(field){
	if(field.parent().find('.icon-remove-sign').length > 0) {
		field.parent().find('.icon-remove-sign').css('visibility','hidden');
		field.parent().parent().removeClass('has-error');
		field.popover('destroy');
		//修改同步的值
		//setChangeValue(field);
	}
}

function onShowDialog(msg){
	bootbox.dialog({
		message: "<span class='bigger-110'>"+msg+"</span>",
		buttons: 			
		{
			"success" :
			 {
				"label" : "<i class='icon-ok'></i> 确定",
				"className" : "btn-sm btn-success",
				"callback": function() {
					//Example.show("great success");
				}
			}
		}
	});
}
